package com.vivianwei.sqlfix;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author wangwei
 * @Date2021/3/10 11:40 上午
 * @Version V1.0
 **/
public abstract class SqlProcess {
    public List<String> tables;
    public String excelPath;
    public String genPath;
    public String sheetName;

    public SqlProcess(List<String> tables, String excelPath, String genPath, String sheetName) {
        this.tables = tables;
        this.excelPath = excelPath;
        this.genPath = genPath;
        this.sheetName = sheetName;
    }

    public void execute() throws SQLException {
//通过sheet名获取

        ExcelReader reader = ExcelUtil.getReader(FileUtil.file
                (excelPath), sheetName);

        List<Map<String, Object>> readAll = reader.readAll();
        for (String tableName : tables) {
            StringBuffer sb = new StringBuffer();
            sb.append(String.format("-- ----------- %s  %s start -------------\n", tableName,sheetName));
            for (Map line : readAll) {
                if (line.get("数据库名称").toString().trim().equals(tableName)) {
                    sb.append(sql(line));
                }
            }
            sb.append(String.format("-- ----------- %s  %s end -------------\n\n", tableName,sheetName));
            if (this instanceof UTF8Process){
                FileUtil.writeUtf8String(sb.toString(),
                        new File(genPath + tableName + "_" + DateUtil.formatDate(new Date()) + ".sql"));

            }else {
                FileUtil.appendUtf8String(sb.toString(),
                        new File(genPath + tableName + "_" + DateUtil.formatDate(new Date()) + ".sql"));
            }
        }
    }

    protected abstract String sql(Map line) throws SQLException;
}
